package vip.meeet.algorithm.str;



public class Num201 {

    public static void main(String[] args) {
//        for(int i=0;i<=100;i++){
//            System.out.println(i+ ":" + Integer.toBinaryString(i));
//        }
//        for(int i = 0;i<32;i++){
////            System.out.print((int)Math.pow(2,i) + ",");
//            System.out.println(i + ":" + (int)Math.pow(2,i));
////            System.out.println(i + ":" + (2<<i));
//        }
//        System.out.println(force(5,7));
//        System.out.println(1<<30);
//        System.out.println((1<<30) * 2);
        System.out.println(rangeBitwiseAnd(5,7));
        System.out.println(rangeBitwiseAnd(2,3));//2
        System.out.println(rangeBitwiseAnd(2,5));
        System.out.println(rangeBitwiseAnd(1,2));
        System.out.println(rangeBitwiseAnd(1,3));
        System.out.println(rangeBitwiseAnd(1,33));
    }

    public static int rangeBitwiseAnd(int m, int n) {
        if(m == 0){
            return 0;
        }
        if(m == n){
            return m;
        }

        for(int i=30;i>0;i--){
            int target = 1 << i;
            if(n == target){
                return 0;
            }
            if(n > target){
                if(m < target){
                    return 0;
                }
                return target + (rangeBitwiseAnd(m % target,n % target));
            }
        }
        return 0;
    }

    public static int force(int m,int n){
        if(m == 0){
            return 0;
        }
        if(m == n){
            return m;
        }
        int result = m;
        for(int i=m + 1;i<=n;i++){
            result = result & i;
        }
        return result;
    }


}
